package org.jeecg.modules.basic.entry.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.apartment.entity.LwgyBaseApartment;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.entry.entity.Apartment;
import org.jeecg.modules.basic.entry.entity.LwgyFjInout;
import org.jeecg.modules.basic.entry.entity.LwgyInoutRecord;
import org.jeecg.modules.basic.entry.entity.LwgyStudentInout;
import org.jeecg.modules.basic.entry.mapper.ApartmentMapper;
import org.jeecg.modules.basic.entry.mapper.LwgyInoutRecordMapper;
import org.jeecg.modules.basic.entry.service.ILwgyElectricControlService;
import org.jeecg.modules.basic.entry.service.ILwgyInoutRecordService;
import org.jeecg.modules.basic.entry.util.SenseTimeToDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * @Description: 出入管理
 * @Author: jeecg-boot
 * @Date:   2020-12-04
 * @Version: V1.0
 */
@Slf4j
@Service
public class LwgyInoutRecordServiceImpl extends ServiceImpl<LwgyInoutRecordMapper, LwgyInoutRecord> implements ILwgyInoutRecordService {

    @Autowired
    private LwgyInoutRecordMapper lwgyInoutRecordMapper;
    @Autowired
    private ApartmentMapper apartmentMapper;
    @Autowired
    private ILwgyElectricControlService iLwgyElectricControlService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public IPage<LwgyStudentInout> stuPageList(Page<LwgyStudentInout> page, QueryWrapper<LwgyStudentInout> queryWrapper) {
        List<LwgyStudentInout> stuList = lwgyInoutRecordMapper.stuPageList(page,queryWrapper);
        if(stuList != null && !stuList.isEmpty()){
            List<LwgyStudentInout> bedList = lwgyInoutRecordMapper.bedPageList();
            stuList.stream().forEach(item -> {
                bedList.stream().forEach(item2 -> {
                    if(item.getStuId().equals(item2.getStuId())){
                        item.setBuildingName(item2.getBuildingName());
                        item.setUnitName(item2.getUnitName());
                        item.setLayerName(item2.getLayerName());
                        item.setRoomName(item2.getRoomName());
                        item.setBedName(item2.getBedName());
                    }
                });
            });
        }
        return page.setRecords(stuList);
    }

    @Override
    public List<LwgyStudentInout> outStuPageList() {
        List<LwgyStudentInout> stuList = lwgyInoutRecordMapper.outStuPageList();
        if(stuList != null && !stuList.isEmpty()){
            List<LwgyStudentInout> bedList = lwgyInoutRecordMapper.bedPageList();
            stuList.stream().forEach(item -> {
                bedList.stream().forEach(item2 -> {
                    if(item.getStuId().equals(item2.getStuId())){
                        item.setBuildingName(item2.getBuildingName());
                        item.setUnitName(item2.getUnitName());
                        item.setLayerName(item2.getLayerName());
                        item.setRoomName(item2.getRoomName());
                        item.setBedName(item2.getBedName());
                    }
                });
            });
        }
        return stuList;
    }

    @Override
    public LwgyBaseStudent queryStuByNumString(String studentNumber){
        return lwgyInoutRecordMapper.queryStuByNumString(studentNumber);
    }

    @Override
    public Boolean stuBindPower(String stuId,String direction, List<Map<String, String>> stuFj){
        try{


        String direction2="";
        String roomId="";
        String xq="";
        String fj="";
        //List<Map<String, String>> stuFj=this.getStudentFjById(stuId);
           if(stuFj.size()>0){
               Map fjmap = stuFj.get(0);
               xq = fjmap.get("xq").toString();
               String lh = fjmap.get("lh").toString();//1、
               String ch = fjmap.get("ch").toString();
               String fjh = fjmap.get("fjh").toString();
               roomId=fjmap.get("roomid").toString();

               String tempLh = extractNumber(lh) + "";
               String tempFjh = extractNumber(fjh)+ "";
               String tempCh = "";// 101101 101001
               if (tempFjh.length() > 3) {
                   tempCh = tempFjh.substring(0, 2);
                   tempFjh = addZeroForNum(
                           Integer.parseInt(tempFjh.substring(2)), 3);
               } else {
                   tempCh = "0" + tempFjh.substring(0, 1);
                   tempFjh = addZeroForNum(
                           Integer.parseInt(tempFjh.substring(1)), 3);
               }
               fj = tempLh.concat(tempCh).concat(tempFjh); // 0101001
               System.out.println("fj:"+fj);
               System.out.println("xq:"+xq);
               //查询宿舍同学最近的进出记录---》修改成按照房间roomid查询房间里学生最近进出情况
               List<Map<String, String>> stuInout=this.roommateInout(roomId);
               System.out.println("宿舍学生最近的进出情况"+stuInout);
               int count=0;
               if(stuInout.size()>0){
                   for(int i=0;i<stuInout.size();i++){
                       Map map= stuInout.get(i);
                       direction2 = map.get("direction").toString();
                       if(direction2.equals("1")){
                           count++;
                       }

                   }
               }
               //目前办公室的表只有这一个房间，为了看到效果，只能固定
               xq="主校区";
               fj="101001";
               //判断是否要开关电
               if(direction.equals("1") && count==1){
                   //学生进，且宿舍就一人，开灯
                   iLwgyElectricControlService.useSBKGData(xq,fj,"1","1");
               }
               if(direction.equals("2") && count==0){
                   //学生出，且宿舍没人，关灯
                   iLwgyElectricControlService.useSBKGData(xq,fj,"2","1");
               }

            }else{//不是学生或者没有住宿，不参与开关电
               return false;
           }

        }catch (Exception e){
            log.error("开关电失败："+e);
            return false;
        }
        return true;
    }

    @Override
    public Boolean stuBindPowerTest(String direction){

        String xq="主校区";
        String fj="101001";
        if(direction.equals("1") ){
            //学生进，开灯
            iLwgyElectricControlService.useSBKGData(xq,fj,"1","1");
        }
        if(direction.equals("2") ){
            //学生出，且宿舍没人，关灯
            iLwgyElectricControlService.useSBKGData(xq,fj,"2","1");
        }
        return true;
    }

    @Override
    public List<Map<String, String>>  getStudentFjById(String userId){

        return lwgyInoutRecordMapper.getStudentFjById(userId);
    }

    @Override
    public List<Map<String, String>> roommateInout(String roomId) {

        return lwgyInoutRecordMapper.roommateInout(roomId);
    }

    public static int extractNumber(String str) {
        if (str == null || str.trim().equals("")) {
            return 0;
        }
        String result = "";
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {
                result += str.charAt(i);
            }
        }
        if (result.trim().equals("")) {
            return 0;
        }
        return Integer.parseInt(result);
    }
    /*
     * 数字不足位数左补0
     *
     * @param str
     *
     * @param strLength
     */
    public static String addZeroForNum(Integer str, int strLength) {
        String result = str.toString();
        int strLen = result.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(result);// 左补0
                // sb.append(str).append("0");//右补0
                result = sb.toString();
                strLen = result.length();
            }
        }
        return result;
    }

    /**
     * 修改房间格式，将校区，楼号转换成电控系统识别101001形式
     */
    public String changeFj(String lh,String fjh){
        String tempLh = extractNumber(lh) + "";
        String tempFjh = extractNumber(fjh)+ "";
        String tempCh = "";// 101101 101001
        if (tempFjh.length() > 3) {
            tempCh = tempFjh.substring(0, 2);
            tempFjh = addZeroForNum(
                    Integer.parseInt(tempFjh.substring(2)), 3);
        } else {
            tempCh = "0" + tempFjh.substring(0, 1);
            tempFjh = addZeroForNum(
                    Integer.parseInt(tempFjh.substring(1)), 3);
        }
        return   tempLh.concat(tempCh).concat(tempFjh); // 0101001
    }

    public IPage<LwgyFjInout> totalPage(Page page, QueryWrapper queryWrapper) {
        return lwgyInoutRecordMapper.totalPage(page, queryWrapper);
    }

    public void powerController(LwgyInoutRecord lwgyInoutRecord){
        String id = lwgyInoutRecord.getUserId();
        String direction = lwgyInoutRecord.getDirection();
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = sdf.format(lwgyInoutRecord.getRecordDate());
        //保存学生最后的开关电的状态
        Integer con = lwgyInoutRecordMapper.updateStuInfo(id,direction,str);

    /*    if(con!=0){//说明是学生，且已经修改
            //获取学生舍友的进出状态
            List<Map<String, String>> roommateDirection=this.getStudentFjById(id);
            int count=0;
            String direction2="";
            String xq="";
            String lh="";
            String fjh="";
            String fj="";
            if(roommateDirection.size()>0){
                for(int i=0;i<roommateDirection.size();i++){
                    Map map= roommateDirection.get(i);
                    xq = map.get("xq").toString();
                    lh = map.get("lh").toString();
                    fjh = map.get("fjh").toString();
                    direction2 = map.get("direction").toString();
                    if(direction2.equals("1")){
                        count++;
                    }
                }
                if(direction.equals("1") && count==1){
                    //学生进，且宿舍就一进状态，开灯
                    fj = changeFj(lh,fjh);
                    iLwgyElectricControlService.useSBKGData(xq,fj,"1","1");
                }
                if(direction.equals("2") && count==0){
                    fj = changeFj(lh,fjh);
                    //学生出，且宿舍没人，关灯
                    iLwgyElectricControlService.useSBKGData(xq,fj,"2","1");
                }
            }
        }*/
    }

    public void powerInApartment(LwgyInoutRecord lwgyInoutRecord) throws ParseException {
        String id = lwgyInoutRecord.getUserId();
        String direction = lwgyInoutRecord.getDirection();
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = sdf.format(lwgyInoutRecord.getRecordDate());
        //保存学生最后的开关电的状态
        Integer con = lwgyInoutRecordMapper.updateStuInfo(id,direction,str);
        if(con!=0){//说明是学生，且已经修改
            //保存到apartment表中
            //获取学生舍友的进出状态（除了本人）
            List<Map<String, String>> roommateDirection=this.getStudentFjById(id);
            int count=0;
            String direction2="";
            String xq="";
            String lh="";
            String fjh="";
            String fj="";
            if(roommateDirection.size()>0){
                for(int i=0;i<roommateDirection.size();i++){
                    Map map= roommateDirection.get(i);
                    xq = map.get("xq").toString();
                    lh = map.get("lh").toString();
                    fjh = map.get("fjh").toString();
                    direction2 = map.get("direction").toString();
                    if(direction2.equals("1")){
                        count++;
                    }
                }
                if(direction.equals("1") && count==0){//本人进，其余学生不在宿舍1进（1开灯）2出（0关灯）0无
                    System.out.println("------开电");
                    String fjcode = this.getFjCodeByFj(xq,lh,fjh);//楼宇名字
                    //学生进，且宿舍就一进状态，开灯，写入表

                    if(oConvertUtils.isNotEmpty(fjcode)) {
                        this.setApartment(xq, SenseTimeToDevice.getLhCode(lh), fjcode, "1");
                    }
                }
                if(direction.equals("2") && count==0){//本人出，其余学生不在宿舍
                    System.out.println("------关电");
                    String fjcode = this.getFjCodeByFj(xq,lh,fjh);//楼宇名字
                    //学生出，且宿舍没人，关灯，写入表

                    if(oConvertUtils.isNotEmpty(fjcode)) {
                        this.setApartment(xq, SenseTimeToDevice.getLhCode(lh), fjcode, "0");
                    }
                }
            }else if(roommateDirection.size()==0){//宿舍里只有他自己

                if(direction.equals("1") ){//本人进
                    System.out.println("------宿舍只有自己，状态进");
                    String fjcode = this.getFjCodeByFj(xq, lh, fjh);//楼宇名字
                    //学生进，且宿舍就一进状态，开灯，写入表

                    if(oConvertUtils.isNotEmpty(fjcode)) {
                        this.setApartment(xq, SenseTimeToDevice.getLhCode(lh), fjcode, "1");
                    }
                }else if(direction.equals("2")){
                    System.out.println("------宿舍只有自己，状态出");
                    String fjcode = this.getFjCodeByFj(xq,lh,fjh);//楼宇名字

                    if(oConvertUtils.isNotEmpty(fjcode)){
                        this.setApartment(xq,SenseTimeToDevice.getLhCode(lh),fjcode,"0");
                    }

                }
            }
        }
    }

    public void setApartment(String xq,String lh,String fjh,String roomState){
        System.out.println("----写入电控数据库中，指定");
        try{
         /*   apartmentMapper.insertOrUpdate(xq,lh,fjh,roomState);*/
            //查询数据库中是否存在该房间的数据
            String a = apartmentMapper.selectSqlServer(xq,lh,fjh,roomState);
            if(oConvertUtils.isNotEmpty(a)){
                //存在，更新
                apartmentMapper.updateSqlServer(xq,lh,fjh,roomState);
            }else{
                //不存在，添加
                apartmentMapper.insertSqlServer(xq,lh,fjh,roomState);
            }
            log.info(" 数据添加到开断电表" + xq+"-"+lh+"-"+fjh+"-"+roomState+"时间："+DateUtils.getTimestamp());

        }catch (Exception e){
            System.out.println("---数据添加到开断电表报错："+e);
        }
    }

    // 临时使用
    public void setApartmentTemp(String xq,String lh,String fjh,String roomState,String syncState){
        System.out.println("----写入电控数据库中，指定");
        try{
            /*   apartmentMapper.insertOrUpdate(xq,lh,fjh,roomState);*/
            //查询数据库中是否存在该房间的数据
            String a = apartmentMapper.selectSqlServer(xq,lh,fjh,roomState);
            if(oConvertUtils.isNotEmpty(a)){
                //存在，更新
                apartmentMapper.updateSqlServerTemp(xq,lh,fjh,roomState,syncState);
            }else{
                //不存在，添加
                apartmentMapper.insertSqlServerTemp(xq,lh,fjh,roomState,syncState);
            }
            log.info(" 数据添加到开断电表" + xq+"-"+lh+"-"+fjh+"-"+roomState+"时间："+DateUtils.getTimestamp());

        }catch (Exception e){
            System.out.println("---数据添加到开断电表报错："+e);
        }
    }
    //通过房间号查询房间code
    public String getFjCodeByFj(String xq,String lh,String fjh){

        String fjhs= xq+'-'+lh+'-'+fjh;
        System.out.println("------查询缓存中房间："+fjhs);
        Object o = redisUtil.get(fjhs);//通过房间信息查询缓存中是否有code值
        if (oConvertUtils.isNotEmpty(o)) {  //取出缓存中的code值
            System.out.println("------缓存中有："+o.toString());
            return o.toString();
        } else {
            //查询房间code对应信息，写入缓存中
            System.out.print("------缓存中没有：");
            String fjcode = apartmentMapper.getFjCode(xq,lh,fjh);
            System.out.println("fjcode");
            Boolean b= redisUtil.set(fjhs, fjcode);//将房间code写入缓存
            return fjcode;

        }
    }

    public List<Apartment> selectList(String xq,String lh,String fjh,String state,String count){
        return apartmentMapper.selectList(xq,lh,fjh,state,count);
    }

    public List<Map<String,Object>> roomShutOff() {
        return apartmentMapper.roomShutOff();
    }

    //在寝室人数统计（按楼宇）
    public List<Map<String, String>> StaOfDormitoryPopulationByBuilding(String id){
        return lwgyInoutRecordMapper.StaOfDormitoryPopulationByBuilding(id);
    }
  //在寝室人数统计（按学院）
    public List<Map<String, String>> StaOfDormitoryPopulationByCollege(String id){
        return lwgyInoutRecordMapper.StaOfDormitoryPopulationByCollege(id);
    }

}
